<?
session_start();
require('libs/class.db.php');
require('libs/class.bibtex.php');
require('libs/class.user.php');
$dbObj = new DB();
$db = $dbObj->getDB();
$bibtex = new Bibtex();
$user = new User($db);


// To return an autocomplete list, echo a file in the following format:
// key1|value1
// key2|value2



switch($_GET['t'])
{
	case 'search':
		echo autocomplete_search($_GET['q']);
	break;
	case 'field':
		echo autocomplete_field($_GET['q'], $_GET['f']);
	break;
	case 'meta':
		echo autocomplete_meta($_GET['q'], $_GET['f']);
	break;
}


function autocomplete_format($in)
{
    $r = '';
    foreach ($in as $k=>$v)
    {
        $r .= "$k|$v\n";
    }
    return $r;
}

function autocomplete_search($q)
{
    global $bibtex;
    $found = $bibtex->search($q,10);   
    $found = $found[0];
    $r = array();
    foreach($found as $f)
    {
        $author = explode(', ', $f['author']);
        $author = $author[0];
        if (count(explode(' and', $f['author'])) > 1)
        {
            $author .= ' et al';
        }
        $r[$f['entrykey']] = $author.' - '.$f['title'];
    }
    return autocomplete_format($r);
}

function autocomplete_field($q, $field)
{
    global $bibtex;
    $found = $bibtex->search($q,10,array($field));   
    $found = $found[0];    
    $r = '';
    foreach($found as $f)
    {
        $r .= $f[$field]."\n";
    }
    return $r;
}

function autocomplete_meta($q, $ID)
{
    global $bibtex;
    global $user;
    $values = $bibtex->metaValues($q, $ID, $user->getID());
	$r = '';
    foreach($values as $v)
    {
        $r .= $v."\n";
    }
	return $r;
}

?>